package com.lh.marketing.canvas.rules;

import com.lh.marketing.canvas.rules.enums.ConditionJoinOperatorEnum;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;

/**
 * 将对象类型的规则引擎转换成表达式
 */
public class ConditionParser {

    /**
     * 将规则对象解析为表达式
     * @param condition 规则对象
     * @return  表达式
     */
    public static String parseToExpression(ConditionEntity condition){
        if(condition == null){
            return "";
        }
        List<ConditionEntity> children = condition.getChildren();
        if(CollectionUtils.isEmpty(children)){
            return "("+condition.getExpression()+")";
        }
        StringBuilder out = new StringBuilder();
        out.append("(");
//        out.append(condition.getExpression());
//        out.append(condition.getJoinOperator().operate);
        deepToParseExpression(children,out);
        out.append(")");
        return out.toString();
    }

    /**
     * 递归解析规则对象
     * @param conditions    规则组
     * @param out   输出字符
     */
    private static void deepToParseExpression(List<ConditionEntity> conditions,StringBuilder out){
        if(CollectionUtils.isEmpty(conditions)){
            return ;
        }
        ConditionJoinOperatorEnum joinOperator = null;
        for (ConditionEntity condition : conditions) {
            if(CollectionUtils.isEmpty(condition.getChildren())){
                //组装表达式
                String expression = joinOperator==null?"":joinOperator.operate;
                out.append(expression).append("(").append(condition.getExpression()).append(")");
                joinOperator = condition.getJoinOperator();
            }else{
                String expression = joinOperator==null?"":joinOperator.operate;
                StringBuilder group = new StringBuilder();
                group.append(expression);
                group.append("(");
                deepToParseExpression(condition.getChildren(),group);
                group.append(")");
                out.append(group);
            }
        }
    }
}
